package com.application.Activity;


import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.DTO.FeelChoiceDTO;
import com.application.DataProvider.ChapterDAO;
import com.application.DataProvider.DetailLearningDAO;

public class FrmDoFeedback extends ListActivity {
	/*--------------các biến layout------------*/
	private ListView listView;
	private Button _btnFeedback;
	private TextView _txtNumberQuestion;
	private TextView _txtTime;
	private TextView _txtTitle;
	private TextView _txtContent;
	private ImageButton _btnNext;
	private ImageButton _btnBack;
	/*--------------các biến thời gian------------*/
	private static int _time_min;
	private int _time_sec;
	private static int _time;

	/*--------------các biến dữ liệu------------*/
	private ArrayAdapter<String> arrayadapter;
	private int _countFeeback = 0;
	private int _feedbackIndex=0;//thu tu cua cau hoi hien tai tre arr cau hoi

	/*---------------các biến khởi tạo feedback one--------------------*/
	private static int _type = 0;//loại feeback
	private static int _idPart = 0;
	private static int _idDetailLearning = 0;
	private static int _idFeelType = 0;
	private static String _title = null;
	private static String _feelchoice = null;

	/*---------------các biến khởi tạo feedback all--------------------*/
	private static String _feel = null;
	private static int _idChap = 0;
	private static int _idClass = 0;

	private ArrayList<Integer> _idPartList = new ArrayList<Integer>(); //danh sách id part
	private ArrayList<Integer> _idDetailLearningList = new ArrayList<Integer>(); //danh sách idDetailLearning tương ứng id part
	private ArrayList<ArrayList<FeelChoiceDTO>> _choiceList; //danh sách các sự lựa chọn tương ứng với feeltype
	private ArrayList<Integer> _choiceListPress = new ArrayList<Integer>(); //danh sách các lựa chọn được chọn
	//private ArrayList<FeelTypeDTO> _typeList; //danh sách các loại lựa chọn
	private ArrayList<Integer> _typeList; //danh sách câu feedback
	private ArrayList<String> _titleList; //danh sách các tiêu đề feedback - tên part
	private Thread _bg;
	private boolean isRunning;
	private AlertDialog.Builder _builder;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frm_dofeedback);

		listView=getListView();

		/*----------------Khởi tạo các biến layout--------------*/
		_btnNext = (ImageButton) findViewById(R.id.dofeedback_btnnext);
		_btnBack = (ImageButton) findViewById(R.id.dofeedback_btnback);
		_btnFeedback = (Button) findViewById(R.id.dofeedback_btnfinish);
		_txtNumberQuestion=(TextView) findViewById(R.id.dofeedback_numberquestion);
		_txtTitle = (TextView) findViewById(R.id.dofeedback_txttitle);
		_txtTime = (TextView) findViewById(R.id.dofeedback_txttime);
		_txtContent = (TextView) findViewById(R.id.dofeedback_txtquestion);

		/*----------------Khởi tạo các biến thời gian--------------*/
		Log.d("PEERDROID", "time do feedback: " + _time);
		_time_min = _time / 60;
		int timemin = _time_min;
		_time_sec = _time - _time_min * 60;

		_builder = new AlertDialog.Builder(this);
		/*----------------Khởi tạo các biến dữ liệu--------------*/
		ArrayList<FeelChoiceDTO> arrchoice = new ArrayList<FeelChoiceDTO>();
		_choiceList = new ArrayList<ArrayList<FeelChoiceDTO>>();
		_typeList = new ArrayList<Integer>();
		_titleList = new ArrayList<String>();

		if(_type == 2) //allfeedback
		{
			getChoiceListFeedbackAll();
		}
		else if(_type == 1) //feedback one
		{
			_idDetailLearningList.add(_idDetailLearning);
			_idPartList.add(_idPart);
			_typeList.add(_idFeelType);
			_titleList.add(_title);
			getChoiceListFeedback();
		}

		initChoiceListPress();
		showTime();
		if(_countFeeback == 1)//chỉ có 1 câu hỏi
		{
			Log.d("PEERDROID","count feedback 1");
			_btnBack.setEnabled(false);
			_btnNext.setEnabled(false);

		}
		else{
			Log.d("PEERDROID","count khac 1");
			_btnBack.setEnabled(false);
		}
		//thiết lập nội dung 

		if(_type == 1)//feedback one
		{
			_txtTitle.setText("Thực hiện phản hồi cho chủ đề "+ _title +" trong thời gian " + timemin + " phút");
		}
		else if(_type == 2)//feedback all
		{
			ChapterDAO cDao = new ChapterDAO(null);
			_txtTitle.setText("Thực hiện phản hồi cho bài học "+ cDao.getName(_idChap) +" trong thời gian " + timemin + " phút");
		}
		_countFeeback = _choiceList.size();
		_feedbackIndex=0;
		ShowQuesion();
		_txtNumberQuestion.setText("Câu "+Integer.toString(_feedbackIndex+1));

		//bat su kien click button next
		_btnNext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				_btnBack.setEnabled(true);
				if(_feedbackIndex<_countFeeback-1){
					if(_feedbackIndex<0)
					{
						_feedbackIndex=0;
					}
					//load next data
					_feedbackIndex=_feedbackIndex+1;
					ShowQuesion();
					_txtNumberQuestion.setText("Câu "+Integer.toString(_feedbackIndex+1));
				}
				if(_feedbackIndex>=_countFeeback-1){

					_btnNext.setEnabled(false);
				}

			}
		});

		//bat su kien click button back
		_btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				_btnNext.setEnabled(true);
				if(_feedbackIndex>0){
					if(_feedbackIndex==_countFeeback)
					{
						_feedbackIndex=_feedbackIndex-1;
					}
					Log.d("PEERDROID","feedback index:" + _feedbackIndex);

					_feedbackIndex=_feedbackIndex-1;
					//load back data
					ShowQuesion();
					_txtNumberQuestion.setText("Câu "+Integer.toString(_feedbackIndex+1));				
				}
				if(_feedbackIndex<=0){
					//btnBack.setVisibility(0);
					_btnBack.setEnabled(false);
				}
			}

		});

		_btnFeedback.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//				 TODO Auto-generated method stub
				doFeedback();
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart do feedback");
		ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
		ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d("PEERDROID","vao ondestroy");
		isRunning = false;
		_bg.stop();
	}


	private void ShowQuesion(){

		String title = "Phản hồi cho chủ đề "+ _titleList.get(_feedbackIndex);
		_txtContent.setText(title);

		ArrayList<String> optionList = new ArrayList<String>();

		for(int i = 0; i < _choiceList.get(_feedbackIndex).size(); i++)
		{
			optionList.add(_choiceList.get(_feedbackIndex).get(i).get_Name());
		}

		//hien thi noi dung
		listView.setEnabled(true);
		listView.setVisibility(View.VISIBLE);
		arrayadapter = new ArrayAdapter<String>(this, R.layout.listrow_singlechoice,R.id.listrow_txtcautraloisingle, optionList);
		listView.setAdapter(arrayadapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.getCheckedItemPosition();

		Log.d("PEERDROID","feedbackIndex: " + _feedbackIndex);
		Log.d("PEERDROID","Choice list show: " + _choiceList.get(_feedbackIndex).toString());
		Log.d("PEERDROID","Choice list press show: " + _choiceListPress.get(_feedbackIndex).toString());
		Log.d("PEERDROID","type list show: " + _typeList.toString());

		//lấy lại giá trị đã check trước đó
		if(_choiceListPress.get(_feedbackIndex) != -1)
			getListView().setItemChecked(_choiceListPress.get(_feedbackIndex), true);
	}

	private void doFeedback()
	{
		isRunning = false;
		_bg.stop();
		//		set data current
		if(get_type() == 1)
		{
			if(_choiceListPress.get(0) != -1)
			{
				Log.d("PEERDROID","Choice list feedback one: " + _choiceList.get(_feedbackIndex).toString());
				Log.d("PEERDROID","Choice list press feedback one: " + _choiceListPress.get(_feedbackIndex).toString());
				Log.d("PEERDROID","type list feedback one: " + _typeList.toString());

				int idchoice = _choiceList.get(0).get(_choiceListPress.get(0)).get_ID();
				//NetworkController.SendFeedbackToTeacher(new Address(NetworkController.get_ipHost()), idchoice, _idDetailLearningList.get(0), NetworkController.get_idLearner());
				NetworkController.SendFeedbackToTeacher(new Address(NetworkController.get_ipHost()), idchoice, _idDetailLearningList.get(0), _idFeelType, NetworkController.get_idLearner());
			}
		}
		else if(get_type() == 2)
		{
			String choiceList = "";
			int n = _choiceListPress.size();
			for(int i = 0; i < n; i++)
			{
				if(_choiceListPress.get(i)!=-1)
				{
					Log.d("PEERDROID","Choice list feedback all: " + _choiceList.get(_feedbackIndex).toString());
					Log.d("PEERDROID","Choice list press feedback all: " + _choiceListPress.get(_feedbackIndex).toString());
					Log.d("PEERDROID","type list feedback all: " + _typeList.toString());
					if(choiceList.length() != 0)
						choiceList += "##";
					int idchoice = _choiceList.get(i).get(_choiceListPress.get(i)).get_ID();
					int iddetail = _idDetailLearningList.get(i);
					int idfeeltype = _typeList.get(i);
					choiceList += iddetail + "/" + idchoice;
				}
			}
			//NetworkController.SendAllFeedbackToTeacher(new Address(NetworkController.get_ipHost()), _idChap, NetworkController.get_idLearner(), choiceList);
			NetworkController.SendAllFeedbackToTeacher(new Address(NetworkController.get_ipHost()), _idChap, NetworkController.get_idLearner(), choiceList);
		}
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		dlDao.updateStatus(_idDetailLearning, false);
		finish();
	}

	private void doEndTime()
	{
		Log.d("PEERDROID","vào do end time");
		//set data current
		_bg.stop();
		_builder.setIcon(R.drawable.img_dialog);
		_builder.setMessage("Đã hết thời gian feedback")
		.setCancelable(false)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				DetailLearningDAO dlDao = new DetailLearningDAO(null);
				dlDao.updateStatus(_idDetailLearning, false);
				finish();
			}
		});
		AlertDialog alert = _builder.create();
		alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
		alert.show();
	}
	//thread can thoi gian lam bai
	private void showTime(){
		Log.d("PEERDROID","vào show time");
		if(_time_sec < 10)
			_txtTime.setText(_time_min + ":0" + _time_sec);
		else
			_txtTime.setText(_time_min + ":" + _time_sec);
		isRunning = true;
		_bg =  new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Log.d("PEERDROID","vào run");
					Log.d("PEERDROID","time" + get_time());
					Log.d("PEERDROID","_time_min" + _time_min);
					Log.d("PEERDROID","_time sec: " + _time_sec);
					while(get_time() > 0 && isRunning) {
						if(_time_sec == 0)
						{
							_time_sec = 60;
							_time_min--;
						}
						Thread.sleep(1000);
						handler.sendMessage(handler.obtainMessage());
					}
					if(isRunning)
						ActivityController.handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								doEndTime();
							}
						}) ;
				}
				catch (Throwable t) {
				}
			}
		});
		_bg.start();
		Log.d("PEERDROID","sau start");
	}
	Handler handler=new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("PEERDROID","Vào hander");
			_time --;
			_time_sec--;
			if(_time_sec < 10)
				_txtTime.setText(_time_min + ":0" + _time_sec);
			else _txtTime.setText(_time_min + ":" + _time_sec);
		}
	};


	void initChoiceListPress()
	{
		int n = _typeList.size();
		for(int i = 0 ; i < n; i++)
			_choiceListPress.add(-1);
	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		_choiceListPress.set(_feedbackIndex, position);
		Log.d("PEERDROID", "_choiceListPress" + _choiceListPress.toString());
	}

	private void getChoiceListFeedback()
	{
		ArrayList<FeelChoiceDTO> arrchoice = new ArrayList<FeelChoiceDTO>();
		String choiceList[] = _feelchoice.split(NetworkController.getSeparator1());
		for(String temp: choiceList)
		{
			String choice[] = temp.split(NetworkController.getSeparator());
			FeelChoiceDTO fcDto = new FeelChoiceDTO(Integer.valueOf(choice[0]), choice[1]);
			arrchoice.add(fcDto);
		}
		_choiceList.add(arrchoice);
	}

	private void getChoiceListFeedbackAll()
	{
		String feelList[] = _feel.split(NetworkController.getSeparator1());
		for(String feel : feelList)
		{
			String temp[] = feel.split(NetworkController.getSeparator());
			_titleList.add(temp[0]);
			_idDetailLearningList.add(Integer.valueOf(temp[1]));
			DetailLearningDAO dlDao = new DetailLearningDAO(null);
			_idPartList.add(dlDao.getIDPart(Integer.valueOf(temp[1])));
			_typeList.add(Integer.valueOf(temp[2]));

			int length = temp.length;
			ArrayList<FeelChoiceDTO> arrchoice = new ArrayList<FeelChoiceDTO>();
			for(int i = 3; i < length; i+=2)
			{
				FeelChoiceDTO fcDto = new FeelChoiceDTO(Integer.valueOf(temp[i]), temp[i+1]);
				arrchoice.add(fcDto);
			}
			_choiceList.add(arrchoice);
		}

	}
	public void addIDPart(int idPart)
	{
		_idPartList.add(idPart);
	}

	public void addIDPart(ArrayList<Integer> idPartList)
	{
		for(int i = 0; i < idPartList.size(); i++)
			_idPartList.add(idPartList.get(i));
	}
	public static void set_idChap(int idChap) {
		_idChap = idChap;
	}

	public static int get_idChap() {
		return _idChap;
	}




	public static void set_idPart(int _idPart) {
		FrmDoFeedback._idPart = _idPart;
	}




	public static int get_idPart() {
		return _idPart;
	}




	public static void set_idDetailLearning(int _idDetailLearning) {
		FrmDoFeedback._idDetailLearning = _idDetailLearning;
	}

	public static int get_idDetailLearning() {
		return _idDetailLearning;
	}

	public static void set_feelchoice(String _feelchoice) {
		FrmDoFeedback._feelchoice = _feelchoice;
	}

	public static String get_feelchoice() {
		return _feelchoice;
	}

	public static void set_type(int _type) {
		FrmDoFeedback._type = _type;
	}

	public static int get_type() {
		return _type;
	}

	public static void set_idClass(int _idClass) {
		FrmDoFeedback._idClass = _idClass;
	}

	public static int get_idClass() {
		return _idClass;
	}

	public static void set_idFeelType(int _idFeelType) {
		FrmDoFeedback._idFeelType = _idFeelType;
	}

	public static int get_idFeelType() {
		return _idFeelType;
	}

	public static void set_title(String _title) {
		FrmDoFeedback._title = _title;
	}

	public static String get_title() {
		return _title;
	}

	public static void set_time(int time) {
		_time = time;
	}

	public static int get_time() {
		return _time;
	}

	public static void set_feel(String _feel) {
		FrmDoFeedback._feel = _feel;
	}

	public static String get_feel() {
		return _feel;
	}
}




















